/**
 * @program: My Application
 * @description: ...
 * @author: Yumaoo
 * @create: 2024-07-03 01:34
 **/
package com.example.myapplication;

import android.content.Context;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.AsyncTask;
import android.widget.Toast;
import okhttp3.*;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class SubmitLocation extends AsyncTask<String, Integer, JSONObject> {
    private String baseUrl = Config.BASE_URL;
    Context context;
    public SubmitLocation(Context context){
        this.context=context;
    }

    @Override
    protected JSONObject doInBackground(String... params) {
        // TODO Auto-generated method stub
        try {
            return postData(params[0]);
        } catch (IOException e) {
            return null;
        }


    }

    protected void onPostExecute(JSONObject json) {

        if (json == null)
        {
            Toast.makeText(context, "Network Error", Toast.LENGTH_LONG).show();
        }
        else {

            try {
                if (json.get("result").equals("success")) {
                    Toast.makeText(context, "Success", Toast.LENGTH_LONG).show();



                } else {
                    Toast.makeText(context, "Failure", Toast.LENGTH_LONG).show();



                }
            } catch (JSONException e) {
                e.printStackTrace();
                Toast.makeText(context, "Network/Server Error", Toast.LENGTH_LONG).show();
            }
        }


    }


    protected void onProgressUpdate(Integer... progress) {

    }

    // 注意：从Android 6.0开始，获取MAC地址需要ACCESS_WIFI_STATE权限，并且在某些设备上可能不返回真实的MAC地址。
// 确保在manifest中声明权限，并在运行时请求权限（如果适用）。
    private String getWifiMacAddress(Context context) {
        String macAddress = null;
        WifiManager wifiMgr = (WifiManager) context.getApplicationContext().getSystemService(Context.WIFI_SERVICE);
        if (wifiMgr != null) {
            WifiInfo wifiInfo = wifiMgr.getConnectionInfo();
            if (wifiInfo != null) {
                macAddress = wifiInfo.getMacAddress();
            }
        }
        // 考虑到兼容性和隐私策略，如果macAddress为null，可能需要备选方案或提示用户。
        return macAddress;
    }
    public JSONObject postData(String jsonData) throws IOException {
        OkHttpClient client = new OkHttpClient();

        // Prepare the POST request data
        String mac = getWifiMacAddress(context);
        RequestBody requestBody = new FormBody.Builder()
                .add("mac", mac)
                .add("data", jsonData)
                .build();

        // Create the request
        Request request = new Request.Builder()
                .url(baseUrl + "submit")
                .post(requestBody)
                .build();

        try (Response response = client.newCall(request).execute()) {
            if (!response.isSuccessful()) {
                throw new IOException("Unexpected code " + response);
            }

            String responseBody = response.body().string();
            return new JSONObject(responseBody);
        } catch (JSONException e) {
            throw new IOException("Error parsing JSON response", e);
        }
    }


}
